package net.keebook.webapp.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.Query;

import net.keebook.webapp.entity.KeeBookAccess;
import net.keebook.webapp.entity.ShareRequest;
import net.keebook.webapp.util.ShareStatus;


@Stateless
public class ShareRequestDao extends Dao<ShareRequest> {
	@Inject
	private KeeBookDao keeBookDao;
	
	@Override
	public void store(ShareRequest item) {
		super.store(item);
	}
	
	@Override
	public void update(ShareRequest item) {
		super.update(item);
	}
	
	@Override
	public ShareRequest get(Long id) {
		return super.get(id);
	}
	
	@Override
	public ShareRequest get(String id) {
		return super.get(id);
	}
	
	@Override
	public void delete(ShareRequest item) {
		super.delete(item);
	}
	
	@SuppressWarnings("unchecked")
	public List<ShareStatus> getShareStatus(Long keeBookId, Long forUserId) {
		
		List<ShareStatus> result = new ArrayList<ShareStatus>();
		
		List<KeeBookAccess> accessList = getKeeBookDao().getAccessListForKeeBook(keeBookId);
		for (KeeBookAccess a : accessList) {
			ShareStatus status = new ShareStatus();
			status.setExposableId(a.getExposableId());
			status.setAccessRight(a.getAccessRight());
			status.setUser(a.getUser().getName());
			status.setStatus(ShareStatus.STATUS_CONFIRMED);
			status.setSelf(forUserId.equals(a.getUser().getId()));
			result.add(status);
		}
		
		Query query = getEntityManager().createQuery("FROM ShareRequest sr WHERE sr.keeBook.id = :keeBookId");
		query.setParameter("keeBookId", keeBookId);
		List<ShareRequest> shareRequestList = (List<ShareRequest>)query.getResultList();
		for (ShareRequest sr : shareRequestList) {
			ShareStatus status = new ShareStatus();
			status.setExposableId(sr.getExposableId());
			status.setAccessRight(sr.getAccessRight());
			status.setUser(sr.getEmail());
			status.setStatus(ShareStatus.STATUS_INVITED);
			status.setSelf(false);
			result.add(status);
		}
		
		Collections.sort(result, new Comparator<ShareStatus>() {
			@Override
			public int compare(ShareStatus o1, ShareStatus o2) {
				return o1.getUser().compareToIgnoreCase(o2.getUser());
			}
		});
		
		return result;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
